package com.hebeiboruan.controller.system;
import com.hebeiboruan.entity.system.RolePower;
import com.hebeiboruan.role.service.RoleService;
import com.hebeiboruan.entity.DTO.system.SearchRoleDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hebeiboruan.role.listener.RoleListener;
import com.hebeiboruan.entity.system.Role;
import com.hebeiboruan.common.HttpMessage;
import com.hebeiboruan.common.exception.CommonException;
import java.time.LocalDateTime;
import com.hebeiboruan.common.exception.ServiceResultEnum;
import com.hebeiboruan.common.exception.system.role.RoleException;
import com.hebeiboruan.common.exception.system.role.RoleResultEnum;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.excel.EasyExcel;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

import com.hebeiboruan.rolePower.service.RolePowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hebeiboruan.common.uitl.LoggerUtil;
@RestController
@RequestMapping("/role")
public class RoleController {
    private static Logger log = LoggerFactory.getLogger(RoleController.class);
    private RoleService roleService;
    private RolePowerService rolePowerService;
    @Autowired
    public void setRolePowerService(RolePowerService rolePowerService) {
        this.rolePowerService = rolePowerService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
    this.roleService = roleService;
    }

    @GetMapping("/getAllRole/{page}/{limit}")
    public HttpMessage getAllRole(@PathVariable Integer page,@PathVariable Integer limit){
        HttpMessage.isBlank(page,limit);
        return HttpMessage.data(roleService.page(new Page<>(page,limit)));
    }

    @PostMapping("/searchRole")
    public HttpMessage searchUser(SearchRoleDTO search){
    HttpMessage.isBlank(search.getPage(),search.getLimit());
    QueryWrapper<Role> wrapper=new QueryWrapper<>();
        if (search.getRoleNo() != null) {
        wrapper.like("role_no",search.getRoleNo());
        }
        if (search.getRoleName() != null) {
        wrapper.like("role_name",search.getRoleName());
        }
    return HttpMessage.data(roleService.page(new Page<>(search.getPage(),search.getLimit()),wrapper));
    }
    @PutMapping("/addRole")
    public HttpMessage addRole(Role role, HttpServletRequest request){
        HttpMessage.isBlank( role.getRoleName());
        try {
            roleService.save(role);
            return HttpMessage.result(ServiceResultEnum.INSERT_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.INSERT_ERROR,e);
        }
    }
    @PostMapping("/editRole")
    public HttpMessage editRole(Role role, HttpServletRequest request){
        HttpMessage.isBlank( role.getRoleName());
        try {
            roleService.updateById(role);
            return HttpMessage.result(ServiceResultEnum.UPDATE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.UPDATE_ERROR,e);
        }
    }
    @DeleteMapping("/removeRole/{roleNo}")
    public HttpMessage removeRole(@PathVariable Integer roleNo,HttpServletRequest request){
        HttpMessage.isBlank(roleNo);
        try {
            roleService.removeById(roleNo);
            return HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            LoggerUtil.webError(e,request,log);
            throw new CommonException(ServiceResultEnum.REMOVE_ERROR,e);
        }

    }
    @DeleteMapping("/batchRemoveRole/{id}")
    public HttpMessage batchRemoveRole(@PathVariable String id){
       HttpMessage.isBlank(id);
        try{
            roleService.removeBatchByIds(Arrays.asList(id.split(",")));
            return HttpMessage.result(ServiceResultEnum.REMOVE_TRUE);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_REMOVE_ERROR,e);
        }

    }

    @PostMapping("/batchAddRole")
    public HttpMessage batchAddRole(@RequestParam("role")List<MultipartFile> role) {
        role.forEach(file->{
                try {
                    EasyExcel.read(file.getInputStream(), Role.class, new RoleListener(roleService)).sheet().doRead();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        return HttpMessage.result(ServiceResultEnum.BATCH_INSERT_TRUE);
    }
        
    @PostMapping("/batchOutRole")
    public void batchOutRole(@RequestParam("role") List<String> role, HttpServletResponse response) throws IOException {
        try{
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        //防止乱码
        String fileName ="D:/"+ URLEncoder.encode("roleData:"+LocalDateTime.now().toString(), "UTF-8").replaceAll("\\+", "%20")+".xlsx";
        List<Role> roleData=new ArrayList<>();
            role.forEach(item->{
                try {
                    roleData.add( new ObjectMapper().readValue(item,Role.class));
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            });
                response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

                EasyExcel.write(response.getOutputStream(), Role.class).autoCloseStream(Boolean.FALSE).sheet("数据").doWrite(roleData);

        }catch (Exception e){
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            response.getWriter().println(HttpMessage.result(ServiceResultEnum.BATCH_OUT_ERROR));
        }
    }
    @GetMapping("/getRolePower/{role}")
    public HttpMessage getRolePower(@PathVariable Integer role){
        HttpMessage.isBlank(role);
        List<RolePower> list = rolePowerService.list(new QueryWrapper<RolePower>().eq("role", role));
        return HttpMessage.data(list);
    }
    @PostMapping("/addRolePower")
    public HttpMessage addRolePower(Integer role,@RequestParam(value="power",required = false) List<Integer> power){
       HttpMessage.isBlank(role);
        List<RolePower> rolePowers=new ArrayList<>();
        try {
            rolePowerService.remove(new QueryWrapper<RolePower>().eq("role",role));
            if (power != null) {
                power.forEach(item->{
                    rolePowers.add(new RolePower(role,item));
                });
                rolePowerService.saveBatch(rolePowers);
            }
            return HttpMessage.data(ServiceResultEnum.INSERT_TRUE);
        }catch (Exception e){
            throw new RoleException(RoleResultEnum.INSERT_POWER_ERROR);
        }
    }
}


